#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <unistd.h>
#include "sem.h"

typedef struct {
    pid_t pid;
    char text[32];
} SHM;

int main(int argc, const char *argv[]) {
    key_t key;
    key = ftok("/", 'x');

    int shmid;
    int semid;
    SHM * myshm;
    shmid = shmget(key, sizeof(SHM), IPC_CREAT | IPC_EXCL | 0664);
    if(shmid == -1) {
        if(errno == EEXIST) {
            shmid = shmget(key, sizeof(SHM), 0664);  //打开
            myshm = shmat(shmid, NULL, 0);           //映射
        } else {
            perror("shmget");
            exit(1);
        
        }
    } else {
        printf("共享内存创建成功\n");
        myshm = shmat(shmid, NULL, 0);      //映射
    }

    semid = semget(key, 2, IPC_CREAT | IPC_EXCL | 0664);
    if(semid == -1) {
        if(errno == EEXIST) {
            printf("信号灯集已存在\n"); 
            semid = semget(key, 2, 0664);
        } else {
            perror("shmget");
            return -1;
        }
    } else {
        printf("信号类集创建成功\n");
        mysem_init(semid, 0, 1);    //初始化信号灯 0
        mysem_init(semid, 1, 0);    //初始化信号灯 1
    }

    while(1) {
        mysem_p(semid, 0);
        fgets(myshm->text, sizeof(myshm->text), stdin);     //向共享内存写入数据
        mysem_v(semid, 1);      //释放信号灯1
        if(strncmp(myshm->text, "quit", 4) == 0) {
            break;
        }
    }

    shmdt(myshm);       //取消映射
    return 0;
}

